package com.sz.biz.logistics.base.service.impl;

import com.sz.biz.common.base.dto.CityModel;
import com.sz.biz.common.base.dto.CountryModel;
import com.sz.biz.common.base.service.AreaManager;
import com.sz.biz.common.base.service.AreaService;
import com.sz.biz.logistics.base.dto.PortDto;
import com.sz.biz.logistics.base.dto.TransportModel;
import com.sz.biz.logistics.base.entity.RegionItem;
import com.sz.biz.logistics.base.service.AirportService;
import com.sz.biz.logistics.base.service.PortService;
import com.sz.biz.logistics.base.service.RegionItemService;
import com.sz.biz.logistics.base.service.RegionService;
import com.sz.common.base.dao.Pagination;
import com.sz.common.base.dao.ParamData;
import com.sz.common.base.dto.QResultDto;
import com.sz.common.base.dto.QueryParams;
import com.sz.common.base.dto.ResultDto;
import com.sz.common.base.dto.TransportIntModel;
import com.sz.common.base.service.AbstractService;
import com.sz.common.base.utils.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Package: com.sz.biz.logistics.base.service.impl <br>
 * Function: TODO: ADD FUNCTION <br>
 * Author: hpeng.wang. <br>
 * Date: 2017-02-15 15:00:00.
 */
@Service
public class RegionItemServiceImpl extends AbstractService implements RegionItemService {
    @Autowired
    private RegionService regionService;
    @Autowired
    private AreaService areaService;

    @Autowired
    private PortService portService;
    @Autowired
    private AirportService airportService;

    @Override
    protected String getMapperNamespace() {
        return "com.sz.biz.logistics.base.mapper.RegionItemMapper";
    }

    /**
     * 根据id查询
     *
     * @param ids
     * @return
     */
    @Override
    public List<RegionItem> findByIds(List<Integer> ids) {
        ParamData paramData = new ParamData();
        paramData.put("ids", ids);
        return dao.findForList(getSqlName("findByIds"), paramData, RegionItem.class);
    }

    @Override
    public void batchSave(List<RegionItem> details) {
        dao.batchInsert(getSqlName("insertSelective"), details);
    }


    @Override
    public List<RegionItem> findByRegionId(Integer id) {
        List<RegionItem> regionItemList = dao.findForList(getSqlName("findByRegionId"), id, RegionItem.class);
        return regionItemList;
    }

    @Override
    public List<RegionItem> findByRegionIds(List<Integer> regionIds) {
        List<RegionItem> list = new ArrayList<>();
        if (regionIds.size() > 0) {
            list = this.findByRegionIds(regionIds, null);
        }
        return list;
    }

    @Override
    public List<RegionItem> findByRegionIds(List<Integer> regionIds, String countryCode) {
        List<RegionItem> list = new ArrayList<>();
        if (!CollectionUtils.isEmpty(regionIds)) {
            ParamData pd = new ParamData();
            pd.put("regionIds", regionIds);
            pd.put("countryCode", countryCode);
            list = dao.findForList(getSqlName("findByRegionIds"), pd, RegionItem.class);
        }
        return list;
    }

    @Override
    public ResultDto findByRegionIds(List<Integer> regionIds, String q, int pageIndex, int pageSize) {
        List<CountryModel> list = new ArrayList<>();
        QResultDto dto = new QResultDto();

        //拼装查询数据
        Pagination page = new Pagination();
        ParamData pd = new ParamData();
        pd.put("q", q);
        pd.put("regionIds", regionIds);
        page.setCurrentPage(pageIndex);
        page.setPageSize(pageSize);
        pd.setPagination(page);

        //从分区表中查询数据
        if (!CollectionUtils.isEmpty(regionIds)) {//当分区id不为空时，再去查询分区item的数据
            list = dao.findForList(getSqlName("findByRegionIdsListPage"), pd, CountryModel.class);
        }

        //如果从分区中找不到国家的数据，那么从国家表中查询出所有的数据
        if (CollectionUtils.isEmpty(list)&& CollectionUtils.isEmpty(regionIds)) {
            ResultDto resultDto = areaService.findCountriesList(new QueryParams(pageSize, pageIndex, q, null, true));
            return resultDto;
        }
        dto.setData(list);
        dto.setPagination(page);
        return dto;
    }

    @Override
    public List<RegionItem> findRegionItemByRegionIdsAndIsActive(String schemaId, Boolean isActive) {
        List<RegionItem> list = new ArrayList<>();
        if (StringUtils.hasLength(schemaId)) {
            List<Integer> ids = regionService.findIdBySchemaUid(schemaId);
            if (!CollectionUtils.isEmpty(ids)) {
                ParamData pd = new ParamData();
                pd.put("ids", ids);
                list = dao.findForList(getSqlName("findRegionItemByRegionIdsAndIsActive"), pd, RegionItem.class);
            }
        }
        return list;
    }


    @Override
    public Map<Integer, List<RegionItem>> findRegionItemMapByRegionIds(List<Integer> regionIds) {
        Map<Integer, List<RegionItem>> mapRegionItem = new HashMap<>();
        List<RegionItem> regionItemList = this.findByRegionIds(regionIds);//根据biz_region的id集合从表biz_region_item中查询出指定id的所有的item
        for (RegionItem regionItem : regionItemList) {
            if (mapRegionItem.get(regionItem.getRegionId()) == null) {
                List<RegionItem> regionItems = new ArrayList<>();
                mapRegionItem.put(regionItem.getRegionId(), regionItems);
            }
            mapRegionItem.get(regionItem.getRegionId()).add(regionItem);
        }
        return mapRegionItem;
    }

    @Override
    public ResultDto findAirByRegionIds(List<Integer> regionIdList, String countryCode, String cityId, String q, int pageIndex, int pageSize, int type) {
        if ("0".equals(cityId)) {
            cityId = null;
        }
        Pagination page = new Pagination();
        page.setCurrentPage(pageIndex);
        page.setPageSize(pageSize);
        //拼装要查询的数据
        ParamData pd = new ParamData();
        pd.put("q", q);
        pd.put("regionIds", regionIdList);
        pd.put("countryCode", countryCode);
        pd.put("cityId", cityId);
        pd.setPagination(page);

        //获取海运或空运的数据
        if (type == 1) { //海运
            if (CollectionUtils.isEmpty(regionIdList)) {
                //当无分区数据时，从港口表中获取数据
                return findPorts(countryCode, cityId, q, pageIndex, pageSize);
            } else { //当分区详情不为空时才去查询
                List<TransportIntModel> returnList = dao.findForList(getSqlName("findPortByRegionIdsListPage"), pd, TransportIntModel.class);
                QResultDto dto = new QResultDto();
                dto.setData(returnList);
                dto.setPagination(page);
                return dto;
            }
        } else { //其它都做空运处理
            if (CollectionUtils.isEmpty(regionIdList)) { //分区为空，从机场表中获取数据
                return findAirports(countryCode, cityId, q, pageIndex, pageSize);
            } else { //当分区详情不为空时才去查询
                List<TransportIntModel> returnList = dao.findForList(getSqlName("findAirPortByRegionIdsListPage"), pd, TransportIntModel.class);
                QResultDto dto = new QResultDto();
                dto.setData(returnList);
                dto.setPagination(page);
                return dto;
            }
        }
    }
    private ResultDto findPorts(String countryCode, String cityId, String q, int pageIndex, int pageSize) {
        List<TransportIntModel> returnList = new ArrayList<>();
        ResultDto ports = portService.findPortShortList(new QueryParams(pageSize, pageIndex, q, null, true).put("countryId", countryCode).put("cityId", cityId));
        if (!ObjectUtils.isEmpty(ports.getData())) {
            List<PortDto> portDtoList = (List<PortDto>) ports.getData();
            for (PortDto portDto : portDtoList) {
                returnList.add(new TransportIntModel(portDto.getId(), portDto.getName(),portDto.getCode(),portDto.getEnglishName()));
            }
        }
        QResultDto dto = new QResultDto();
        dto.setData(returnList);
        dto.setPagination(((QResultDto) ports).getPagination());
        return dto;
    }

    private ResultDto findAirports(String countryCode, String cityId, String q, int pageIndex, int pageSize) {
        List<TransportIntModel> returnList = new ArrayList<>();
        ResultDto airports = airportService.shortAirportListPage(new QueryParams(pageSize, pageIndex, q, null, true).put("countryId", countryCode).put("cityId", cityId));
        if (!ObjectUtils.isEmpty(airports.getData())) {
            List<TransportModel> airportDtoList = (List<TransportModel>) airports.getData();
            if (!CollectionUtils.isEmpty(airportDtoList)) {
                for (TransportModel portDto : airportDtoList) {
                    returnList.add(new TransportIntModel(Integer.parseInt(portDto.getId()), portDto.getName(),portDto.getTriadCode()));
                }
            }
        }
        QResultDto dto = new QResultDto();
        dto.setData(returnList);
        dto.setPagination(((QResultDto) airports).getPagination());
        return dto;
    }


    @Override
    public int findAreaNullCountByRegionIds(List<Integer> regionIds, String countryCode) {
        int count = 0;
        if (!CollectionUtils.isEmpty(regionIds) && !StringUtils.isEmpty(countryCode)) {
            ParamData pd = new ParamData();
            pd.put("countryCode", countryCode);
            pd.put("regionIds", regionIds);
            count = (int) dao.findForObject(getSqlName("findAreaNullCountByRegionIds"), pd);
        }
        return count;
    }


    @Override
    public ResultDto findCityModelByRegionIds(List<Integer> regionIds, String countryCode, String q, int pageIndex, int pageSize) {
        List<CityModel> list = new ArrayList<>();
        QResultDto dto = new QResultDto();
        Pagination page = new Pagination();
        if (regionIds.size() > 0) {
            ParamData pd = new ParamData();
            pd.put("q", q);
            pd.put("regionIds", regionIds);
            pd.put("countryCode", countryCode);
            page.setCurrentPage(pageIndex);
            page.setPageSize(pageSize);
            pd.setPagination(page);
            list = dao.findForList(getSqlName("findCityModelByRegionIdsListPage"), pd, CityModel.class);
        }
        dto.setData(list);
        dto.setPagination(page);
        return dto;
    }
}
